/**
 * RenweiWu
 * NoCardCountingService.java
 * 2017年9月6日
 * NoCardCountingService
 * TODO
 * 
 */
package com.etrans.web.gps.business.report.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.report.domain.LngLat;
import com.etrans.web.gps.business.report.domain.TouristVehicleOutGuiyang;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.DateUtil;
import com.mongodb.QueryOperators;

/**
 * @Description:TODO
 * @author RenweiWu
 * @date 2017年9月6日
 * @ClassName:  NoCardCountingService  
 * @param:   
 */

@Service
public class NoCardCountingService extends BaseService{
	@Autowired
	private CommonService commonService;
	private static SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd"); 
	@Autowired
	private Config config;
	

	public @ResponseBody Map<String,Object> queryNoCardCounting(int area_id,String vehicle_no,String enterpirseName,String startTime,String endTime){
		Map<String,Object> map =new HashMap<String, Object>();
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		List<String> namelist = null;
		namelist = new ArrayList<String>();
		List<HashMap<String,Object>> lists =commonService.queryEnterAndPlatByRole(area_id,null);
		for (HashMap<String, Object> hashMap : lists){
			if(enterpirseName==null||"".equals(enterpirseName)){
				namelist.add((String)hashMap.get("entName"));
			}else{
				String name =(String)hashMap.get("entName");
				if(enterpirseName.equals(name)){
					namelist.add(enterpirseName);
				}
			}
		}
		if(vehicle_no!=null&&!"".equals(vehicle_no)){
			String vehicle = vehicle_no.split("_")[0];
			String color = vehicle_no.split("_")[1];
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("selected", area_id);
			param.put("vehicle_no",vehicle);
			param.put("vehicle_color",color);	
			List<HashMap<String,Object>> list =commonService.queryVeListByRole(param);
			if(list!=null){
				for (HashMap<String, Object> hashMap : list) {
					if(hashMap.get("vehicle_no").equals(vehicle)){
						whereMap.put("vehicle_no",vehicle);
						whereMap.put("vehicle_color",Integer.parseInt(color));
					}
				}
			}
		}else{
			HashMap<String,Object> nameMap = new HashMap<String,Object>();
			nameMap.put(QueryOperators.IN,namelist);
			whereMap.put("enterprise_name",nameMap);
		}
		HashMap<String,Object> timeMap = new HashMap<String,Object>();
		if(startTime!=null&&!"".equals(startTime)&&endTime!=null&&!"".equals(endTime)){
			if(startTime.equals(endTime)){
				timeMap.put(QueryOperators.GTE,DateUtil.getISODate(startTime+" 00:00:00"));
				timeMap.put(QueryOperators.LTE,DateUtil.getISODate(endTime+" 23:59:59"));
			}else{
				if(startTime!=null&&!"".equals(startTime)){
					timeMap.put(QueryOperators.GTE,DateUtil.getStringToDate(startTime));
				}
				if (endTime!=null&&!"".equals(endTime)) {
					timeMap.put(QueryOperators.LTE,DateUtil.getStringToDate(endTime));
				}
			}
		}else {
			if (endTime!=null&&!"".equals(endTime)) {
				try {
					timeMap.put(QueryOperators.GTE,DF.parse((DateUtil.getDateToString(new Date(),null))));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		whereMap.put("analyse_date",timeMap);
		List<TouristVehicleOutGuiyang> list = new ArrayList<TouristVehicleOutGuiyang>();
		List<Document> dist= MGTemplete.findDocuments("egov","tourist_vehicle_out_guiyang", whereMap);
    	for (Document document : dist) {
    		Document doc = (Document) document.get("coordinates");
    		LngLat lgla = MGTemplete.toBean(doc, LngLat.class); 
    		TouristVehicleOutGuiyang tours = MGTemplete.toBean(document, TouristVehicleOutGuiyang.class);
    		tours.setLnglat(lgla);
    		list.add(tours);
    	}
		Map<String,Integer> rsmap = new HashMap<String,Integer>();
		for (TouristVehicleOutGuiyang rs : list) {
			if(rsmap.get(rs.getEnterprise_name()) != null){
				rsmap.put(rs.getEnterprise_name(),(int)rsmap.get(rs.getEnterprise_name())+1);
			}else{
				rsmap.put(rs.getEnterprise_name(),1);
			}
		}
		List<String>  barXAxisData =new ArrayList<String>();
		List<Integer>  barSeriesData =new ArrayList<Integer>();
		for (Entry<String, Integer> entry :rsmap.entrySet()) {
			barXAxisData.add(entry.getKey());
			barSeriesData.add(entry.getValue());
		}
		map.put("series", barSeriesData);
		map.put("xAxisData", barXAxisData);
		return map;
	}
	
	
	public @ResponseBody PageVo queryTables(int area_id,Map<String,Object> maps){		
		String enterpirseName = (String)maps.get("enterpirseName");
		String vehicle_no  = (String)maps.get("vehicleId");
		String startTime  = (String)maps.get("startTime");
		String endTime  = (String)maps.get("endTime");
		int pageSize = (int)maps.get("pageSize");
		int page = (int)maps.get("page");
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		List<String> namelist = null;
		namelist = new ArrayList<String>();
		List<HashMap<String,Object>> lists =commonService.queryEnterAndPlatByRole(area_id,null);
		for (HashMap<String, Object> hashMap : lists){
			if(enterpirseName==null||"".equals(enterpirseName)){
				namelist.add((String)hashMap.get("entName"));
			}else{
				String name =(String)hashMap.get("entName");
				if(enterpirseName.equals(name)){
					namelist.add(enterpirseName);
				}
			}
		}
		if(vehicle_no!=null&&!"".equals(vehicle_no)){
			String vehicle = vehicle_no.split("_")[0];
			String color = vehicle_no.split("_")[1];
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("selected", area_id);
			param.put("vehicle_no",vehicle);
			param.put("vehicle_color",color);	
			List<HashMap<String,Object>> list =commonService.queryVeListByRole(param);
			if(list!=null){
				for (HashMap<String, Object> hashMap : list) {
					if(hashMap.get("vehicle_no").equals(vehicle)){
						whereMap.put("vehicle_no",vehicle);
						whereMap.put("vehicle_color",Integer.parseInt(color));
					}
				}
			}
		}else{
			HashMap<String,Object> nameMap = new HashMap<String,Object>();
			nameMap.put(QueryOperators.IN,namelist);
			whereMap.put("enterprise_name",nameMap);
		}
		HashMap<String,Object> timeMap = new HashMap<String,Object>();
		if(startTime!=null&&!"".equals(startTime)&&endTime!=null&&!"".equals(endTime)){
			if(startTime.equals(endTime)){
				timeMap.put(QueryOperators.GTE,DateUtil.getISODate(startTime+" 00:00:00"));
				timeMap.put(QueryOperators.LTE,DateUtil.getISODate(endTime+" 23:59:59"));
			}else{
				if(startTime!=null&&!"".equals(startTime)){
					timeMap.put(QueryOperators.GTE,DateUtil.getStringToDate(startTime));
				}
				if (endTime!=null&&!"".equals(endTime)) {
					timeMap.put(QueryOperators.LTE,DateUtil.getStringToDate(endTime));
				}
			}
		}else {
			if (endTime!=null&&!"".equals(endTime)) {
				try {
					timeMap.put(QueryOperators.GTE,DF.parse((DateUtil.getDateToString(new Date(),null))));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		whereMap.put("analyse_date",timeMap);
		HashMap< String,Object> sortMap = new HashMap<String,Object>();
		sortMap.put("analyse_date",Constant.MONGODB_DESC);
		List<Document> dist = MGTemplete.findDocumentsByPage("egov","tourist_vehicle_out_guiyang", whereMap,sortMap,page,pageSize);
		List<TouristVehicleOutGuiyang> list = new ArrayList<TouristVehicleOutGuiyang>();
    	for (Document document : dist) {
    		Document doc = (Document) document.get("coordinates");
    		LngLat lgla = MGTemplete.toBean(doc, LngLat.class); 
    		TouristVehicleOutGuiyang tours = MGTemplete.toBean(document, TouristVehicleOutGuiyang.class);
    		tours.setLnglat(lgla);
    		list.add(tours);
    	}
		int i=1;
		for (TouristVehicleOutGuiyang touris : list) {
			touris.setIndex(i);
			touris.setOutLocation(this.getLocation(touris.getLnglat()));
			i++;
		}
		Long count = MGTemplete.findCount("egov","tourist_vehicle_out_guiyang", whereMap);
		PageVo vo = new PageVo();
		vo.setRows(list);
		vo.setTotal(new Long(count).intValue());
		vo.setPage(page);
		return vo;
	}	
	
	
	
	
	public  String getLocation(LngLat coordinates){
		StringBuffer buff = new StringBuffer();
		String URL =config.addressPath+"?location="+coordinates.getCoordinates()[0]+","+coordinates.getCoordinates()[1];
		HttpPost httpPost = new HttpPost(URL);
		CloseableHttpClient client = HttpClientBuilder.create().build();
		String str =null;
		try {
			HttpResponse response = client.execute(httpPost);

				InputStream in = response.getEntity().getContent();
				InputStreamReader isr = new InputStreamReader(in);
				BufferedReader bfr =new  BufferedReader(isr);
				while((str=bfr.readLine())!=null){
					buff.append(str);
				}
				bfr.close();
			JSONObject json = JSONObject.parseObject(buff.toString());
			str = json.get("regeocodes").toString();
			str = str.substring(1,str.length()-1);
			json = JSONObject.parseObject(str);
			str = json.get("formatted_address").toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
}
